package com.xhu.collegestudentrentalsystem.module.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xhu.collegestudentrentalsystem.module.user.dao.HouseDAO;
import com.xhu.collegestudentrentalsystem.module.user.dao.UserMarkDAO;
import com.xhu.collegestudentrentalsystem.module.user.entity.House;
import com.xhu.collegestudentrentalsystem.module.user.entity.Page;
import com.xhu.collegestudentrentalsystem.module.user.entity.UserMark;
import com.xhu.collegestudentrentalsystem.module.user.service.IMarkService;
import com.xhu.collegestudentrentalsystem.util.constant.EntityProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhu huilin
 * @date 2023/3/12 15:23
 */
@Service
public class MarkServiceImpl implements IMarkService {

    @Autowired
    private UserMarkDAO userMarkDAO;

    @Autowired
    private HouseDAO houseDAO;

    /**
     * 根据房子id和用户id，查询数据库中是否存在收藏记录
     * @param houseId 房子id
     * @param userId  用户id
     * @return
     */
    @Override
    public UserMark findUserMarkById(Long houseId, Long userId) {
        UserMark userMark = userMarkDAO.selectOne(new QueryWrapper<UserMark>()
                                        .eq(EntityProperty.mark.HOUSE_ID, houseId)
                                        .eq(EntityProperty.mark.USER_ID, userId));
        return userMark;
    }

    /**
     * 用户收藏房子
     */
    @Override
    public Integer markHouse(UserMark userMark) {
        int result = userMarkDAO.insert(userMark);
        return result;
    }

    /**
     * 用户取消收藏该房子
     */
    @Override
    public Integer cancelMarkHouse(UserMark userMark) {
        int result = userMarkDAO.delete(new QueryWrapper<UserMark>()
                                        .eq(EntityProperty.mark.HOUSE_ID, userMark.getHouseId())
                                        .eq(EntityProperty.mark.USER_ID, userMark.getUserId()));
        return result;
    }

    /**
     * 查询用户的收藏列表
     */
    @Override
    public List<House> findUserMarkList(Long userId, Page page) {
        List<UserMark> marks = userMarkDAO.selectList(new QueryWrapper<UserMark>().eq(EntityProperty.mark.USER_ID, userId));
        if(marks.isEmpty()){
            return null;
        }
        // 得到marks的房子id列表
        Long[] houseIds = new Long[marks.size()];
        int i = 0;
        for (UserMark mark : marks) {
            houseIds[i++] = mark.getHouseId();
        }
        // 查询并返回 房子信息（分页）
        PageHelper.startPage(page.getCurrent() , page.getLimit());
        List<House> houses = houseDAO.selectList(new QueryWrapper<House>().in(EntityProperty.ID, houseIds));
        Integer count = houseDAO.selectCount(new QueryWrapper<House>().in(EntityProperty.ID, houseIds));
        page.setRows(count);
        return houses;
    }
}
